<template>
  <div>
    <!-- 搜索表单 -->
    <el-form :model="searchParams">
      <el-form-item>
        <div style="display: flex; gap: 10px;">
          <div>
            <label>Assessment</label>
            <el-select v-model="searchParams.assessment" placeholder="请选择">
              <el-option
                  v-for="assessment in assessments"
                  :key="assessment.id"
                  :label="assessment.title"
                  :value="assessment.id"
              />
            </el-select>
          </div>

          <div>
            <label>状态</label>
            <el-select v-model="searchParams.status" placeholder="请选择">
              <el-option label="可用" :value="2"></el-option>
              <el-option label="弃用" :value="1"></el-option>
            </el-select>
          </div>

          <div>
            <label>维度</label>
            <el-select v-model="searchParams.type" placeholder="请选择">
              <el-option label="JP" :value="1"></el-option>
              <el-option label="TF" :value="2"></el-option>
              <el-option label="SN" :value="3"></el-option>
              <el-option label="EL" :value="4"></el-option>
            </el-select>
          </div>

          <el-button type="primary" @click="search">搜索</el-button>
          <el-button type="primary" @click="openModal('add')">添加题目</el-button>
        </div>
      </el-form-item>
    </el-form>



    <!-- 题目表格 -->
    <el-table :data="questions"  style="width: 100%">
      <el-table-column  label="序号" width="60">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="title" label="题目内容" width="400"></el-table-column>
      <el-table-column label="维度" width="80">
        <template slot-scope="scope">
          <span :style="{color: getDimensionColor(scope.row.type)}">{{ getDimensionLabel(scope.row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="难度" width="200">
        <template slot-scope="scope">
          <el-rate v-model="scope.row.difficulty" disabled show-score :max="5" :allow-half="true"></el-rate>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="110">
        <template slot-scope="scope">
          <span>{{ scope.row.status === 2 ? '可用' : '弃用' }}</span>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="400">
        <template slot-scope="scope">
          <el-button size="mini" @click="openModal('view', scope.row)">查看</el-button>
          <el-button size="mini" @click="openModal('edit', scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="deleteQuestion(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        align="center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 15px;"
    ></el-pagination>

    <!-- 弹出框 -->
    <el-dialog :visible.sync="isDialogVisible" :title="modalTitle" width="600px">
      <el-form :model="editForm" label-width="120px" class="dialog-form">
        <!-- 题目内容 -->
        <el-form-item label="题目内容">
          <el-input v-model="currentQuestion.title" :disabled="isViewMode"></el-input>
        </el-form-item>

        <!-- 难度 -->
        <el-form-item label="难度">
          <el-rate
              v-model="currentQuestion.difficulty"
              :max="5"
              :allow-half="true"
              :disabled="isViewMode"
              show-score
              style="color: #f56c6c;"
          ></el-rate>
        </el-form-item>

        <!-- 维度 -->
        <el-form-item label="维度">
          <el-select
              v-model="currentQuestion.type"
              placeholder="请选择"
              :disabled="isViewMode"
              style="width: 100%;"
          >
            <el-option label="JP" :value="1"></el-option>
            <el-option label="TF" :value="2"></el-option>
            <el-option label="SN" :value="3"></el-option>
            <el-option label="EL" :value="4"></el-option>
          </el-select>
        </el-form-item>

        <!-- 提示 -->
        <el-form-item label="提示">
          <el-input
              v-model="currentQuestion.hint"
              :disabled="isViewMode"
              placeholder="请输入提示信息"
          ></el-input>
        </el-form-item>

        <!-- 状态选择 -->
        <el-form-item label="状态">
          <el-select
              v-model="currentQuestion.status"
              placeholder="请选择状态"
              :disabled="isViewMode"
              style="width: 100%;"
          >
            <el-option label="可用" :value="2"></el-option>
            <el-option label="弃用" :value="1"></el-option>
          </el-select>
        </el-form-item>

        <!-- 答案选项 -->
        <el-form-item label="答案选项">
          <!-- 遍历选项 -->
          <div
              v-for="(choice, index) in currentQuestion.choicesList"
              :key="index"
              style="display: flex; align-items: center; margin-bottom: 10px;"
          >
            <!-- 输入框显示选项内容，若为查看模式则禁用输入框 -->
            <el-input
                v-model="choice.title"
                :disabled="isViewMode"
                :style="{ color: choice.checked === 1 && isViewMode ? 'red' : 'black' }"
                placeholder="请输入选项内容"
                style="flex-grow: 1; margin-right: 10px;"
            ></el-input>

            <!-- Radio按钮用于标记正确答案 -->
            <el-radio
                v-model="choice.checked"
                :label="1"
                :disabled="isViewMode"
                style="margin-right: 10px;"
            ></el-radio>

            <!-- 删除按钮，只有在非查看模式下显示 -->
            <el-button
                v-if="!isViewMode"
                type="danger"
                icon="el-icon-delete"
                @click="removeOption(index)"
            ></el-button>
          </div>

          <!-- 添加选项按钮，只有在非查看模式下显示 -->
          <el-button
              v-if="!isViewMode"
              type="primary"
              @click="addOption"
              style="margin-top: 10px;"
          >添加选项</el-button>
        </el-form-item>
      </el-form>

        <!-- 模态框底部操作按钮 -->
      <div slot="footer" class="dialog-footer" style="text-align: right; padding: 10px 20px;">
        <el-button @click="isDialogVisible = false">取消</el-button>
        <el-button v-if="!isViewMode" type="primary" @click="handleModalConfirm">
          {{ modalAction === 'add' ? '添加' : '确认' }}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getAssessments } from '@/api/assess/assessment';
import {addTopics, getTopics, updateTopics, deleteTopics} from "@/api/assess/topic";

export default {
  data() {
    return {
      searchParams: {
        assessment: null,
        status: null,
        type: null,
      },
      editForm: {
        assessmentId: '' // 新增或修改时的选中的 assessment
      },
      assessments: [],  // 存储 assessment 列表
      isDialogVisible: false, // 控制模态框是否显示
      questions: [], // 题目列表
      total: 0,
      currentPage: 1,
      pageSize: 5,
      modalTitle: '', // 模态框标题
      modalAction: '', // 当前操作类型 (add, edit, view)
      isViewMode: false, // 是否为查看模式
      currentQuestion: {
        title: '',
        assessmentId: null,
        difficulty: 0,
        type: null,
        status: 2,
        hint: '',
        choicesList: [{
          questionId: 1,
          title: '',
          checked: 0,
        }], // 答案选项数组
      },
    };
  },
  methods: {
    // 获取维度颜色
    getDimensionColor(type) {
      const colors = {
        1: 'red',
        2: 'green',
        3: 'blue',
        4: 'purple',
      };
      return colors[type] || 'black';
    },
    // 获取维度标签
    getDimensionLabel(type) {
      const labels = {
        1: 'JP',
        2: 'TF',
        3: 'SN',
        4: 'EL',
      };
      return labels[type] || '';
    },
    // 搜索
    search() {
      const params = {
        assessment: this.searchParams.assessment || null,
        status: this.searchParams.status || null,
        type: this.searchParams.type || null,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
      };
      getTopics(params)
          .then(res => {
            this.questions = res.data.records;
            this.total = res.data.total;
          })
          .catch(err => {
            console.error('获取题目列表失败', err);
          });
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.search();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.search();
    },
    openModal(action, question = {}) {
      this.modalAction = action;
      this.modalTitle = action === 'add' ? '添加题目' : action === 'edit' ? '修改题目' : '查看题目';
      this.isViewMode = action === 'view'; // 设置是否是查看模式

      if (action === 'add') {
        // 如果是新增题目，初始化一个空题目
        this.currentQuestion = {
          title: '',
          assessmentId: null,
          difficulty: 0,
          type: null,
          hint: '',
          correctOption: null,
          choicesList: [{ title: '', checked: 0 }],
        };
      } else {
        console.log(question)
        // 编辑或查看题目时，深拷贝传入的题目数据
        this.currentQuestion = JSON.parse(JSON.stringify(question));
      }

      this.isDialogVisible = true; // 打开模态框
    },
    addOption() {
      this.currentQuestion.choicesList.push({ title: '', checked: 0 });
    },
    removeOption(index) {
      this.currentQuestion.choicesList.splice(index, 1);
    },
    handleModalConfirm() {
      // 根据操作类型进行不同的处理
      if (this.modalAction === 'add') {
        // 准备添加新题目的数据
        const newQuestion = {
          ...this.currentQuestion,
          index: this.questions.length + 1, // 根据现有题目数量设置索引
        };

        console.log(newQuestion);
        // 假设有一个 API 方法 addQuestion 用于发送 POST 请求
        addTopics(newQuestion)
            .then(response => {
              // 如果成功，更新问题列表
              this.questions.push(response.data); // 假设返回的数据结构包含新添加的题目
              this.isDialogVisible = false; // 关闭模态框
              this.$message.success('添加成功!');
              this.search(); // 更新题目列表
            })
            .catch(err => {
              console.error('添加题目失败', err); // 处理错误
            });
      } else if (this.modalAction === 'edit') {
        // 准备修改现有题目的数据
        const index = this.questions.findIndex(q => q.index === this.currentQuestion.index);
        console.log(this.currentQuestion)
        if (index !== -1) {
          // 假设有一个 API 方法 updateQuestion 用于发送 PUT 请求
          updateTopics(this.currentQuestion)
              .then(response => {
                // 更新问题列表
                this.questions.splice(index, 1, response.data); // 更新为返回的最新数据
                this.isDialogVisible = false; // 关闭模态框
                this.$message.success('修改成功!');
                this.search(); // 更新题目列表
              })
              .catch(err => {
                console.error('修改题目失败', err); // 处理错误
              });
        }
      }
    },

    deleteQuestion(question) {
      // 确认用户是否真的要删除
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端接口删除题目
        deleteTopics(question) // 假设 question 对象中有 id 字段
            .then(response => {
              // 如果成功，更新题目列表
              this.questions = this.questions.filter(q => q.id !== question.id); // 更新本地列表
              this.$message.success('删除成功!');
            })
            .catch(err => {
              console.error('删除题目失败', err);
              this.$message.error('删除失败，请重试!');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 获取 assessments 列表的方法
    fetchAssessments() {
      getAssessments()
          .then(response => {
            this.assessments = response.data; // 赋值给 assessments 数据属性
          })
          .catch(error => {
            console.error('获取 assessments 失败:', error);
          });
    }
  },
  created() {
    this.search();
    this.fetchAssessments();
  }
};
</script>

<style>
.dialog-form {
  padding: 20px;
}
.dialog-footer {
  background-color: #f9fafc;
}
</style>
